package response

import (
	"net/http"

	"github.com/kataras/iris/v12"
)

type SseResponse struct {
	ctx     iris.Context
	flusher http.Flusher
}

func NewSse(ctx iris.Context) (*SseResponse, bool) {
	flusher, ok := ctx.ResponseWriter().Flusher()

	sse := &SseResponse{
		ctx:     ctx,
		flusher: flusher,
	}

	// set header
	if ok {
		sse.ctx.ContentType("text/event-stream")
		sse.ctx.Header("Cache-Control", "no-cache")
		sse.ctx.Header("Connection", "keep-alive")
	}

	return sse, ok
}

func (sse *SseResponse) WriteJson(v any) {
	if sse.ctx != nil && sse.flusher != nil {
		// write data
		sse.ctx.Writef("data: ")
		sse.ctx.JSON(v)
		sse.ctx.Writef("\n")

		sse.flusher.Flush()
	}
}

func (sse *SseResponse) Writef(format string, a ...any) {
	if sse.ctx != nil && sse.flusher != nil {
		// write data
		sse.ctx.Writef("data: "+format, a...)
		sse.ctx.Writef("\n")

		sse.flusher.Flush()
	}
}

func (sse *SseResponse) Ping(v any) {

}
